package com.ljh.localmusic.data.local

import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import androidx.annotation.WorkerThread
import com.ljh.localmusic.data.local.models.AudioItem
import com.ljh.localmusic.utils.ext.logd
import kotlin.collections.plusAssign

/**
 * author：LJH on 2025/8/15 16:18
 *
 */
class ContentResolverHelper(
    private val context: Context
) {
    private var mCursor: Cursor? = null

    private val projection: Array<String> = arrayOf(
        MediaStore.Audio.AudioColumns._ID,
        MediaStore.Audio.AudioColumns.DISPLAY_NAME,
        MediaStore.Audio.AudioColumns.ARTIST,
        MediaStore.Audio.AudioColumns.DATA,
        MediaStore.Audio.AudioColumns.DURATION,
        MediaStore.Audio.AudioColumns.TITLE,
        MediaStore.Audio.Media.ALBUM_ID // <--- 添加这一行
    )

//    private var selectionClause: String? = "${MediaStore.Audio.AudioColumns.IS_MUSIC} = ?"

    //    private var selectionClause: String? = "${MediaStore.Audio.AudioColumns.IS_MUSIC} = ?"
    private var selectionClause: String? =
        "${MediaStore.Audio.AudioColumns.IS_MUSIC} = ? AND " +
                "${MediaStore.Audio.AudioColumns.DISPLAY_NAME} NOT LIKE '%.kgm' AND " +
                "${MediaStore.Audio.AudioColumns.DISPLAY_NAME} NOT LIKE '%.vpr' AND " +  // 酷狗的另一种格式
                "${MediaStore.Audio.AudioColumns.DISPLAY_NAME} NOT LIKE '%.ncm'"      // 网易云音乐的加密格式

    private var selectionArg = arrayOf("1")
    private val sortOrder = "${MediaStore.Audio.AudioColumns.DISPLAY_NAME} ASC"


    @WorkerThread
    fun getAudioData(): List<AudioItem> {
        return getCursorData()
    }

    private fun getCursorData(): List<AudioItem> {
        val audioList = mutableListOf<AudioItem>()
        mCursor = context.contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selectionClause,
            selectionArg,
            sortOrder
        )

        mCursor?.use { cursor ->
            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns._ID)
            val displayNameColumn =
                cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DISPLAY_NAME)
            val artistColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.ARTIST)
            val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA)
            val durationColumn =
                cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DURATION)
            val titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.TITLE)
            // 2. 获取 ALBUM_ID 列的索引
            val albumIdColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.ALBUM_ID)

            cursor.apply {
                if (count == 0) {
                    Log.i("Cursor", "getCursorData: ")
                } else {
                    while (cursor.moveToNext()) {
                        val id = getLong(idColumn)
                        val displayName = getString(displayNameColumn)
                        val artist = getString(artistColumn)
                        val data = getString(dataColumn)
                        val duration = getInt(durationColumn)
                        val title = getString(titleColumn)
                        val uri = ContentUris.withAppendedId(
                            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                            id
                        )
                        // 3. 从 cursor 中获取 albumId
                        val albumId = getLong(albumIdColumn)
                        // 4. 构建专辑封面的 Uri
                        val artworkUri = ContentUris.withAppendedId(
                            Uri.parse("content://media/external/audio/albumart"),
                            albumId
                        )
                        "11title:$title,duration:$duration,coverPath:${artworkUri}".logd()
                        if (duration > 66 * 1000){
                            audioList += AudioItem(
                                id, uri, displayName, artist, duration, title, data, artworkUri
                            )
                        }
                    }
                }
            }
        }
        return audioList
    }
}